import 'package:flutter/material.dart';
import 'package:pp_uikit/multi_list/pp_selection_single_list.dart';
import 'package:pp_uikit/multi_list/pp_selection_util.dart';
import 'package:pp_uikit/pp_selection_entity.dart';
import 'package:pp_uikit/pp_uikit_utils.dart';
import 'package:pp_uikit/theme/pp_selection_theme.dart';

typedef PPOnRangeSelectionConfirm = void Function(
    PPSelectionEntity entity, int firstIndex, int secondIndex, int thirdIndex);

class PPMultiListViewController extends ChangeNotifier {
  void refreshData() {
    notifyListeners();
  }
}

// ignore: must_be_immutable
class PPMultiListView extends StatefulWidget {
  PPMultiListViewController? controller;
  final PPSelectionEntity entity;
  final double maxContentHeight;
  PPSelectionTheme? themeData;
  final PPOnRangeSelectionConfirm? onSelectionConfirm;

  /// 每列占比
  List<int>? flexs;

  PPMultiListView({
    Key? key,
    required this.entity,
    this.maxContentHeight = DESIGN_SELECTION_HEIGHT,
    required this.onSelectionConfirm,
    this.themeData,
    this.controller,
    this.flexs,
  }) : super(key: key) {
    themeData ??= PPSelectionTheme();
    entity.configRelationshipAndDefaultValue();
  }

  @override
  State<StatefulWidget> createState() => PPMultiListViewState();
}

class PPMultiListViewState extends State<PPMultiListView> {
  List<PPSelectionEntity> _firstList = [];
  List<PPSelectionEntity> _secondList = [];
  List<PPSelectionEntity> _thirdList = [];
  List<PPSelectionEntity> _originalSelectedItemsList = [];
  int _firstIndex = -1;
  int _secondIndex = -1;
  int _thirdIndex = -1;

  int totalLevel = 0;

  @override
  void initState() {
    _initData();
    super.initState();
    // 监听
    widget.controller?.addListener(() {
      // 遍历数据源，设置真正选中的index
      _configDefaultSelectedData();
      // 使用真正选中的index来刷新数组
      _refreshDataSource();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      constraints: const BoxConstraints(maxHeight: DESIGN_SELECTION_HEIGHT),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        children: _listWidget(),
      ),
    );
  }

  List<Widget> _listWidget() {
    List<Widget> widgets = [];

    if (!PPUIKitUtils.isEmpty(_firstList) &&
        PPUIKitUtils.isEmpty(_secondList) &&
        PPUIKitUtils.isEmpty(_thirdList)) {
      /// 1、仅有一级的情况
      /// 1.1 一级单选 && 没有自定义范围的情况
      widgets.add(PPSelectionSingleListWidget(
          items: _firstList,
          themeData: widget.themeData!,
          backgroundColor: _getBgByListIndex(1),
          selectedBackgroundColor: _getSelectBgByListIndex(1),
          maxHeight: widget.maxContentHeight,
          flex:
              widget.flexs != null ? widget.flexs![0] : _getFlexByListIndex(1),
          focusedIndex: _firstIndex,
          singleListItemSelect:
              (int listIndex, int index, PPSelectionEntity entity) {
            _setFirstIndex(index);
            if (widget.onSelectionConfirm != null) {
              widget.onSelectionConfirm!(
                  entity, _firstIndex, _secondIndex, _thirdIndex);
            }
          }));
    } else if (!PPUIKitUtils.isEmpty(_firstList) &&
        !PPUIKitUtils.isEmpty(_secondList) &&
        PPUIKitUtils.isEmpty(_thirdList)) {
      /// 2、有二级的情况
      widgets.add(PPSelectionSingleListWidget(
          items: _firstList,
          themeData: widget.themeData!,
          backgroundColor: _getBgByListIndex(1),
          selectedBackgroundColor: _getSelectBgByListIndex(1),
          flex:
              widget.flexs != null ? widget.flexs![0] : _getFlexByListIndex(1),
          focusedIndex: _firstIndex,
          singleListItemSelect:
              (int listIndex, int index, PPSelectionEntity entity) {
            _setFirstIndex(index);
          }));

      widgets.add(PPSelectionSingleListWidget(
          items: _secondList,
          themeData: widget.themeData!,
          backgroundColor: _getBgByListIndex(2),
          selectedBackgroundColor: _getSelectBgByListIndex(2),
          flex:
              widget.flexs != null ? widget.flexs![1] : _getFlexByListIndex(2),
          focusedIndex: _secondIndex,
          singleListItemSelect:
              (int listIndex, int index, PPSelectionEntity entity) {
            _setSecondIndex(index);
            if (widget.onSelectionConfirm != null) {
              widget.onSelectionConfirm!(
                  entity, _firstIndex, _secondIndex, _thirdIndex);
            }
          }));
    } else if (!PPUIKitUtils.isEmpty(_firstList) &&
        !PPUIKitUtils.isEmpty(_secondList) &&
        !PPUIKitUtils.isEmpty(_thirdList)) {
      /// 3、有三级的情况
      widgets.add(PPSelectionSingleListWidget(
          items: _firstList,
          themeData: widget.themeData!,
          backgroundColor: _getBgByListIndex(1),
          selectedBackgroundColor: _getSelectBgByListIndex(1),
          flex:
              widget.flexs != null ? widget.flexs![0] : _getFlexByListIndex(1),
          focusedIndex: _firstIndex,
          singleListItemSelect:
              (int listIndex, int index, PPSelectionEntity entity) {
            _setFirstIndex(index);
          }));

      widgets.add(PPSelectionSingleListWidget(
          items: _secondList,
          themeData: widget.themeData!,
          backgroundColor: _getBgByListIndex(2),
          selectedBackgroundColor: _getSelectBgByListIndex(2),
          flex:
              widget.flexs != null ? widget.flexs![1] : _getFlexByListIndex(2),
          focusedIndex: _secondIndex,
          singleListItemSelect:
              (int listIndex, int index, PPSelectionEntity entity) {
            _setSecondIndex(index);
          }));
      widgets.add(PPSelectionSingleListWidget(
          items: _thirdList,
          themeData: widget.themeData!,
          backgroundColor: _getBgByListIndex(3),
          selectedBackgroundColor: _getSelectBgByListIndex(3),
          flex:
              widget.flexs != null ? widget.flexs![2] : _getFlexByListIndex(3),
          focusedIndex: _thirdIndex,
          singleListItemSelect:
              (int listIndex, int index, PPSelectionEntity entity) {
            if (entity.isSelected) {
              _thirdIndex = index;
            } else {
              _thirdIndex = -1;
            }
            setState(() {});
            if (widget.onSelectionConfirm != null) {
              widget.onSelectionConfirm!(
                  entity, _firstIndex, _secondIndex, _thirdIndex);
            }
          }));
    }

    return widgets;
  }

  /// 初始化数据
  void _initData() {
    // 生成筛选节点树
    _originalSelectedItemsList = widget.entity.selectedList();
    for (PPSelectionEntity entity in _originalSelectedItemsList) {
      entity.isSelected = true;
      if (entity.customMap != null) {
        entity.originalCustomMap = Map.from(entity.customMap!);
      }
    }

    // 初始化每列的选中 index 为 -1，未选中。
    _configDefaultInitSelectIndex();
    // 遍历数据源，设置真正选中的index
    _configDefaultSelectedData();
    // 使用真正选中的index来刷新数组
    _refreshDataSource();
  }

  // 设置默认无选中项的时候默认选择index
  void _configDefaultInitSelectIndex() {
    _firstIndex = _secondIndex = _thirdIndex = -1;
  }

  void _configDefaultSelectedData() {
    _firstList = widget.entity.children;
    //是否已选择的item里面有第一列的
    if (_firstList.isEmpty) {
      _secondIndex = -1;
      _secondList = [];

      _thirdIndex = -1;
      _thirdList = [];

      return;
    }
    _firstIndex = _getInitialSelectIndex(_firstList);

    if (_firstIndex >= 0 && _firstIndex < _firstList.length) {
      _secondList = _firstList[_firstIndex].children;
      _secondIndex = _getInitialSelectIndex(_secondList);
    }

    if (_secondList.isEmpty) {
      _thirdIndex = -1;
      _thirdList = [];
      return;
    }
    if (_secondIndex >= 0 && _secondIndex < _secondList.length) {
      _thirdList = _secondList[_secondIndex].children;
      if (_thirdList.isNotEmpty) {
        _thirdIndex = _getInitialSelectIndex(_thirdList);
      }
    }
  }

  ///还原数据选中状态
  void _resetSelectionData(PPSelectionEntity entity) {
    entity.isSelected = false;
    entity.customMap = {};
    if (PPSelectionFilterType.range == entity.filterType) {
      entity.title = '';
    }
    for (PPSelectionEntity subEntity in entity.children) {
      _resetSelectionData(subEntity);
    }
  }

  ///数据还原
  void _restoreOriginalData() {
    for (PPSelectionEntity commonEntity in _originalSelectedItemsList) {
      commonEntity.isSelected = true;
      commonEntity.customMap = Map.from(commonEntity.originalCustomMap);
    }
  }

  Color _getBgByListIndex(int listIndex) {
    Color deepNormalBgColor = widget.themeData!.deepNormalBgColor;
    Color middleNormalBgColor = widget.themeData!.middleNormalBgColor;
    Color lightNormalBgColor = widget.themeData!.lightNormalBgColor;
    if (totalLevel == 1) {
      return lightNormalBgColor;
    } else if (totalLevel == 2) {
      if (listIndex == 1) {
        return middleNormalBgColor;
      } else {
        return lightNormalBgColor;
      }
    } else {
      if (listIndex == 1) {
        return deepNormalBgColor;
      } else if (listIndex == 2) {
        return middleNormalBgColor;
      } else if (listIndex == 3) {
        return lightNormalBgColor;
      }
    }
    return lightNormalBgColor;
  }

  Color _getSelectBgByListIndex(int listIndex) {
    Color deepSelectBgColor = widget.themeData!.deepSelectBgColor;
    Color middleSelectBgColor = widget.themeData!.middleSelectBgColor;
    Color lightSelectBgColor = widget.themeData!.lightSelectBgColor;
    if (totalLevel == 1) {
      return lightSelectBgColor;
    } else if (totalLevel == 2) {
      if (listIndex == 1) {
        return middleSelectBgColor;
      } else {
        return lightSelectBgColor;
      }
    } else {
      if (listIndex == 1) {
        return deepSelectBgColor;
      } else if (listIndex == 2) {
        return middleSelectBgColor;
      } else if (listIndex == 3) {
        return lightSelectBgColor;
      }
    }
    return lightSelectBgColor;
  }

  /// 默认占比为 1，
  /// 其中一列、两列情况下，占比都是 1
  /// 当为三列数据时，占比随着 listIndex 增加而增大。为 3：3：4 比例水平占据屏幕
  int _getFlexByListIndex(int listIndex) {
    int flex = 1;
    if (totalLevel == 1 || totalLevel == 2) {
      flex = 1;
    } else if (totalLevel == 3) {
      if (listIndex == 1) {
        flex = 3;
      } else if (listIndex == 2) {
        if (_thirdList.isEmpty) {
          flex = 7;
        } else {
          flex = 3;
        }
      } else if (listIndex == 3) {
        flex = 4;
      }
    }
    return flex;
  }

  void _setFirstIndex(int firstIndex) {
    _firstIndex = firstIndex;
    _secondIndex = -1;
    _thirdIndex = -1;
    if (widget.entity.children.length > _firstIndex) {
      List<PPSelectionEntity> seconds =
          widget.entity.children[_firstIndex].children;
      _secondIndex = _getInitialSelectIndex(seconds);
      if (_secondIndex >= 0) {
        _setSecondIndex(_secondIndex);
      }
    }
    setState(() {
      _refreshDataSource();
    });
  }

  void _setSecondIndex(int secondIndex) {
    _secondIndex = secondIndex;
    _thirdIndex = -1;
    List<PPSelectionEntity> seconds =
        widget.entity.children[_firstIndex].children;
    if (seconds.length > _secondIndex) {
      List<PPSelectionEntity> thirds = seconds[_secondIndex].children;
      if (thirds.isNotEmpty) {
        _thirdIndex = _getInitialSelectIndex(thirds);
      }
    }
    setState(() {
      _refreshDataSource();
    });
  }

  // 刷新3个ListView的数据源
  void _refreshDataSource() {
    _firstList = widget.entity.children;
    if (_firstIndex >= 0 && _firstList.length > _firstIndex) {
      _secondList = _firstList[_firstIndex].children;
      if (_secondIndex >= 0 && _secondList.length > _secondIndex) {
        _thirdList = _secondList[_secondIndex].children;
      } else {
        _thirdList = [];
      }
    } else {
      _secondList = [];
      _thirdList = [];
    }
  }

  int _getInitialSelectIndex(List<PPSelectionEntity> levelList) {
    int index = -1;
    if (levelList.isEmpty) {
      return index;
    }

    for (PPSelectionEntity entity in levelList) {
      if (entity.isSelected) {
        index = levelList.indexOf(entity);
        break;
      }
    }

    /// 非跨区域选择时，走此方法设置默认选择 index
    if (index < 0) {
      for (PPSelectionEntity entity in levelList) {
        if (entity.isUnLimit() &&
            PPSelectionUtil.getTotalLevel(entity) > 1 &&
            !(entity.parent?.hasCheckBoxBrother() ?? false)) {
          index = levelList.indexOf(entity);
          break;
        }
      }
    }
    return index;
  }
}
